package com.zzc.emotisenseclassroom.dbservice.user.impl;

import com.github.pagehelper.PageHelper;
import com.zzc.ZzcException.ParamNullException;
import com.zzc.baseRepository.componet.CommonSqlBuider;
import com.zzc.baseRepository.componet.WhereConditionEnum;
import com.zzc.baseRepository.componet.Wheres;
import com.zzc.baseRepository.componet.interfaces.BaseDbService;
import com.zzc.emotisenseclassroom.common.domainexception.UserIdNoNumber;
import com.zzc.emotisenseclassroom.dao.user.UserDao;
import com.zzc.emotisenseclassroom.dbservice.user.UserDbService;
import com.zzc.emotisenseclassroom.domain.user.dto.GetStudentIdAndNameReqDTO;
import com.zzc.emotisenseclassroom.domain.user.vo.StudentIdAndNameVO;
import com.zzc.emotisenseclassroom.dto.user.StudentDTO;
import com.zzc.emotisenseclassroom.dto.user.UserDTO;
import com.zzc.emotisenseclassroom.enums.UserTypeEnum;
import com.zzc.emotisenseclassroom.pojo.UserLogin;
import com.zzc.emotisenseclassroom.pojo.UserRegister;
import com.zzc.emotisenseclassroom.utils.ConstantUtil;
import com.zzc.emotisenseclassroom.utils.MD5Util;
import com.zzc.utils.Verify;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Copyright Zzc
 * FileName: UserDbServiceImpl
 * Author:   Zzc
 * Date:     2024/4/1815:17
 * Description:用户数据库业务层实现类
 * hISTORY:
 * <author>  <time>     <version>    <desc>
 * 作者姓名   修改时间       版本号       描述
 * Zzc                   1.0.0
 */
@Service
public class UserDbServiceImpl extends BaseDbService<UserDao> implements UserDbService {
    private int checkPassWord(UserLogin userLogin) {
        if (StringUtils.isBlank(userLogin.getPassWord()) || StringUtils.isBlank(userLogin.getAccountNumber())) {
            return 0;
        }
        return baseDao.checkPassWord(userLogin);
    }

    @Override
    public UserDTO getUserInfo(UserLogin userLogin) {
        if (StringUtils.isBlank(userLogin.getPassWord()) || StringUtils.isBlank(userLogin.getAccountNumber())) {
            return null;
        }

        // 账号是主键，一定有且只有一个
        /*int count = checkPassWord(userLogin);
        if (count != 1){
            return null;
        }*/

        CommonSqlBuider commonSqlBuider = new CommonSqlBuider();
        commonSqlBuider.selectFrom(UserDao.class);
        commonSqlBuider.select(UserDao.getSelectFields());
        Wheres where = commonSqlBuider.where();
        where.andWhere(UserDao.ACCOUNT_NUMBER, WhereConditionEnum.EQ, userLogin.getAccountNumber());
        where.andWhere(UserDao.PASSWORD, WhereConditionEnum.EQ, MD5Util.toMD5(userLogin.getPassWord()));
        List<UserDTO> list = baseDao.list(commonSqlBuider, UserDTO.class);
        return !Verify.isEmpty(list) ? list.get(0) : null;
    }

    @Override
    public Long checkAccountNumberIsExists(Long accountNumber) {
        CommonSqlBuider commonSqlBuider = new CommonSqlBuider();
        commonSqlBuider.selectFrom(UserDao.class);
        commonSqlBuider.select(UserDao.ACCOUNT_NUMBER);
        Wheres where = commonSqlBuider.where();
        where.andWhere(UserDao.ACCOUNT_NUMBER, WhereConditionEnum.EQ, String.valueOf(accountNumber));
        List<UserRegister> list = baseDao.list(commonSqlBuider, UserRegister.class);
        return !Verify.isEmpty(list) ? Long.valueOf(list.get(0).getAccountNumber()) : null;
    }

    @Override
    public void userRegister(UserRegister userRegister) {
        if (StringUtils.isBlank(userRegister.getAccountNumber()) || StringUtils.isBlank(userRegister.getPassWord())) {
            throw new ParamNullException();
        }
        userRegister.setPassWord(MD5Util.toMD5(userRegister.getPassWord()));
        baseDao.insert(userRegister);
    }

    @Override
    public int updateUserInfo(UserDTO userDTO) {
        if (userDTO.getAccountNumber() == null) {
            return 0;
        }

        Wheres wheres = new Wheres();
        wheres.andWhere(UserDao.ACCOUNT_NUMBER, WhereConditionEnum.EQ, userDTO.getAccountNumber());
        return baseDao.update(userDTO, wheres);
    }

    @Override
    public UserDTO getUserInfoByUserId(Long schoolId, Long classId, Long userId) {
        if (schoolId == null || classId == null || userId == null) {
            return null;
        }
        CommonSqlBuider commonSqlBuider = new CommonSqlBuider();
        commonSqlBuider.selectFrom(UserDao.class);
        commonSqlBuider.select(UserDao.getSelectFields());
        Wheres where = commonSqlBuider.where();
        where.andWhere(UserDao.SCHOOL_ID, WhereConditionEnum.EQ, String.valueOf(schoolId));
        where.andWhere(UserDao.CLASS_ID, WhereConditionEnum.EQ, String.valueOf(classId));
        where.andWhere(UserDao.USER_ID, WhereConditionEnum.EQ, String.valueOf(userId));
        List<UserDTO> list = baseDao.list(commonSqlBuider, UserDTO.class);
        return !Verify.isEmpty(list) ? list.get(0) : null;
    }

    @Override
    public List<StudentDTO> getStudentListBySchoolAndClass(Long schoolId, Long classId, Integer pageNum, Integer pageSize) {
        CommonSqlBuider commonSqlBuider = new CommonSqlBuider();
        commonSqlBuider.selectFrom(UserDao.class);
        commonSqlBuider.select(UserDao.getStudentInfoFields());
        Wheres where = commonSqlBuider.where();
        where.andWhere(UserDao.SCHOOL_ID, WhereConditionEnum.EQ, String.valueOf(schoolId));
        where.andWhere(UserDao.CLASS_ID, WhereConditionEnum.EQ, String.valueOf(classId));
        where.andWhenIn(UserDao.USER_TYPE, WhereConditionEnum.IN, Collections.singletonList(UserTypeEnum.STUDENT.getType()));
        PageHelper.startPage(pageNum, pageSize);

        return baseDao.list(commonSqlBuider, StudentDTO.class);
    }

    @Override
    public List<StudentDTO> getStudentListByCondition(Map<String, Object> param) {
        Long schoolId = Long.parseLong(param.get("schoolId").toString());
        Long classId = Long.parseLong(param.get("classId").toString());
        Integer pageNum = (Integer) param.get("pageNum");
        Integer pageSize = (Integer) param.get("pageSize");
        Object realName = param.get("realName");
        Object userId = param.get("userId");
        CommonSqlBuider commonSqlBuider = new CommonSqlBuider();
        commonSqlBuider.selectFrom(UserDao.class);
        commonSqlBuider.select(UserDao.getStudentInfoFields());
        Wheres where = commonSqlBuider.where();
        where.andWhere(UserDao.SCHOOL_ID, WhereConditionEnum.EQ, String.valueOf(schoolId));
        where.andWhere(UserDao.CLASS_ID, WhereConditionEnum.EQ, String.valueOf(classId));
        where.andWhenIn(UserDao.USER_TYPE, WhereConditionEnum.IN, Collections.singletonList(UserTypeEnum.STUDENT.getType()));
        if (realName != null && StringUtils.isNotBlank(realName.toString())) {
            where.andWhenLike(UserDao.REAL_NAME, WhereConditionEnum.LIKE, realName.toString());
        }
        if (userId != null && StringUtils.isNotBlank(userId.toString())) {
            Long tempUserId = null;
            try {
                tempUserId = Long.parseLong(userId.toString());
            } catch (Exception e) {
                throw new UserIdNoNumber();
            }
            where.andWhere(UserDao.USER_ID, WhereConditionEnum.EQ, tempUserId.toString());
        }
        PageHelper.startPage(pageNum, pageSize);

        return baseDao.list(commonSqlBuider, StudentDTO.class);
    }

    @Override
    public int countStudent(Long schoolId, Long classId) {
        if (schoolId == null || classId == null) {
            return 0;
        }

        return baseDao.countStudent(schoolId, classId);
    }

    @Override
    public List<StudentIdAndNameVO> getStudentIdAndNameList(GetStudentIdAndNameReqDTO reqDTO) {
        if (reqDTO.getClassId() == null || reqDTO.getSchoolId() == null) {
            return Collections.emptyList();
        }

        CommonSqlBuider sqlBuilder = new CommonSqlBuider();
        sqlBuilder.selectFrom(UserDao.class);
        sqlBuilder.select(UserDao.USER_ID);
        sqlBuilder.select(UserDao.REAL_NAME);
        Wheres where = sqlBuilder.where();
        where.andWhere(UserDao.SCHOOL_ID, WhereConditionEnum.EQ, String.valueOf(reqDTO.getSchoolId()));
        where.andWhere(UserDao.CLASS_ID, WhereConditionEnum.EQ, String.valueOf(reqDTO.getClassId()));
        where.andWhere(UserDao.USER_TYPE, WhereConditionEnum.EQ, String.valueOf(UserTypeEnum.STUDENT.getType()));

        List<StudentIdAndNameVO> resultList = new ArrayList<>();

        int pageNum = 1;
        while (true) {
            PageHelper.startPage(pageNum++, ConstantUtil.LIST_SIZE);
            List<StudentIdAndNameVO> tempList = baseDao.list(sqlBuilder, StudentIdAndNameVO.class);
            if (!Verify.isEmpty(tempList)) {
                resultList.addAll(tempList);
            }
            if (Verify.isEmpty(tempList) || tempList.size() < ConstantUtil.LIST_SIZE) {
                break;
            }
        }
        return resultList;
    }

    @Override
    public int conditionCountStudent(Map<String, String> requestData) {
        String classIdStr = requestData.get("classId");
        Long classId = StringUtils.isNotBlank(classIdStr) ? Long.parseLong(classIdStr) : null;
        String schoolIdStr = requestData.get("schoolId");
        Long schoolId = StringUtils.isNotBlank(schoolIdStr) ? Long.parseLong(schoolIdStr) : null;
        if (classId == null || schoolId == null) {
            return 0;
        }
        String userIdStr = requestData.get("userId");
        Long userId = null;
        try {
            userId = StringUtils.isNotBlank(userIdStr) ? Long.parseLong(userIdStr) : null;
        } catch (Exception e) {
            throw new UserIdNoNumber();
        }

        String realName = requestData.get("realName");

        return baseDao.conditionCountStudent(schoolId, classId, userId, realName);
    }
}
